import axios from 'axios';
import qs from 'qs';
const validateStatus = (status) => {
    return status >= 200 && status < 300;
};
axios.defaults.timeout = 6000;
axios.defaults.withCredentials = true; // 设置允许跨域设置cookie
// 开发环境下给定，生产环境删除
axios.defaults.baseURL = process.env.NODE_ENV === 'production' ? '/apis' : '/apis';
//axios.defaults.baseURL = 'http://192.168.6.11:9010'
axios.defaults.validateStatus = validateStatus;
axios.defaults.headers['Content-Type'] ='application/json';
axios.defaults.headers['x-requested-with'] ='XMLHttpRequest';
let cancel;
const promiseArr = {};
// http request 拦截器
axios.interceptors.request.use(
    (config) => {
        //发起请求时，取消掉当前正在进行的相同请求
        if (promiseArr[config.url]) {
            promiseArr[config.url]('操作取消');
            promiseArr[config.url] = cancel;
        } else {
            promiseArr[config.url] = cancel;
        }
        config.headers.token = localStorage.getItem('TOKEN') || '';
        if(config.headers['Content-Type']=='application/x-www-form-urlencoded'){
            config.data = qs.stringify(config.data);
        }
        return config;
    },
    (err) => {
        return Promise.reject(err);
    }
);

// http request 拦截器
axios.interceptors.response.use(
    (resp) => {
        // const { code, msg } = resp.data;
        // if (!validateStatus(code) && code !== undefined) { //返回错误状态
        //     return Promise.reject(msg);
        // }
        return resp;
    },
    (err) => {
        if(err.response.status === 401){
           
        }
        return Promise.reject(err);
    }
);

export default axios;
